'use strict'
const path = require('path')
// npminstall =》 自动安装依赖的三方库
const npminstall = require('npminstall')
const pakDir = require('pkg-dir').sync
const { formatPath, getNpmLatestVersion } = require('@medlog-cli-dev/utils')
const pathExists = require('path-exists').sync

class Package {
  constructor(options) {
    if (
      !options ||
      Object.prototype.toString.call(options) !== '[object Object]'
    ) {
      throw new Error('参数不能为空')
    }
    this.targetPath = options.targetPath
    this.storeDir = options.storeDir
    this.packageName = options.packageName
    this.packageVersion = options.packageVersion
    // 缓存的前缀
    this.cacheFilePathPreFix = this.packageName.replace('/', '_')
  }
  exists() {
    if (this.storeDir) {
      this._prepare()
      return pathExists(this.cacheFilePath)
    } else {
      return pathExists(this.targetPath)
    }
  }
  async install() {
    await this._prepare()
    const data = {
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: 'https://registry.npmjs.org',
      pkgs: [
        {
          name: this.packageName,
          version: this.packageVersion,
        },
      ],
    }
    console.log('data', data)
    return npminstall(data)
  }
  async update() {
    await this._prepare()
    // 1. 当前最新的npm模块版本号
    const latestPackageVersion = await getNpmLatestVersion(this.packageName)
    // 当前最新版本号对应的路径
    const latestFilePath = this.getSpecificCacheFilePath(latestPackageVersion)
    // 2. 查询最新版本号对应的路径是否存在，如果不存在，则直接安装最新版本
    if (!pathExists(latestFilePath)) {
      await npminstall({
        root: this.targetPath,
        storeDir: this.storeDir,
        registry: 'https://registry.npmjs.org',
        pkgs: [
          {
            name: this.packageName,
            version: latestPackageVersion,
          },
        ],
      })
      this.packageVersion = latestPackageVersion
    } else {
      this.packageVersion = latestPackageVersion
    }
    return latestFilePath
  }
  // 获取init的根路径
  getRootFilePath() {
    // 1. 获取package.json所在目录 pkg-dir
    const dir = pakDir(this.targetPath)
    if (dir) {
      // 2. 读取package.json
      const pkgFile = require(path.resolve(dir, 'package.json'))
      // 3. 寻找main
      if (pkgFile && pkgFile.main) {
        // 4. 路径兼容
        return formatPath(path.resolve(dir, pkgFile.main))
      }
    }
    return null
  }

  get cacheFilePath() {
    return this.getSpecificCacheFilePath(this.packageVersion)
  }
  getSpecificCacheFilePath(packageVersion) {
    return path.resolve(
      this.storeDir,
      `_${this.cacheFilePathPreFix}@${packageVersion}@${this.packageName}`
    )
  }

  async _prepare() {
    if (this.storeDir && !pathExists(this.storeDir)) {
      fse.mkdirpSync(this.storeDir)
    }
    // 将外界传的latest转为最新版本
    if (this.packageVersion === 'latest') {
      this.packageVersion = await getNpmLatestVersion(this.packageName)
    }
  }
}
module.exports = Package
